package net.csdn.business.kanban.common.filter;

import com.alibaba.fastjson2.JSON;
import io.opentracing.Span;
import io.opentracing.util.GlobalTracer;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.kanban.common.constant.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
public class LogFilter implements Filter {
    private static final String DEFAULT_BODY = "unknown";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        HttpServletRequest req=(HttpServletRequest) request;
        String traceInfo=req.getHeader("uber-trace-id");
        ContentCachingRequestWrapper httpWrapper = new ContentCachingRequestWrapper(req);
       /* String traceId = httpWrapper.getHeader(CommonConstants.TRACE_ID);
        if(StringUtils.isNotBlank(traceId)){
            MDC.put(CommonConstants.TRACE_ID, traceId);
        }*/
        try {
            // 设置 Jaeger Span 的 OperationName
            Span span = GlobalTracer.get().activeSpan();
            if (span != null) {
                span.setOperationName(((HttpServletRequest) request).getRequestURI());
            }
            wrapperResponse(((HttpServletResponse) response));
            chain.doFilter(httpWrapper, response);
            // 设置 Jaeger Span 的 OperationName
            span = GlobalTracer.get().activeSpan();
            if (span != null) {
                span.setOperationName(((HttpServletRequest) request).getRequestURI());
            }
        } finally {
            log.info("request path:{} ip:{} method:{} query:{} body:{} cost:{} traceInfo:{}", httpWrapper.getRequestURI(), httpWrapper.getRemoteAddr(), httpWrapper.getMethod(), getParam(httpWrapper), getBody(httpWrapper), System.currentTimeMillis() - start,traceInfo);
            MDC.remove(CommonConstants.TRACE_ID);
        }
    }

    private String getBody(ContentCachingRequestWrapper servletRequest) {
        // 这里读取不到数据，数据流是不可重复读(使用spring自带的ContentCachingRequestWrapper content-type=multipart/form-data 获取不到请求内容)
        try {
            return JSON.toJSONString(new String(servletRequest.getContentAsByteArray()));
        } catch (Exception ignored) {

        }
        return DEFAULT_BODY;
    }

    private String getParam(ContentCachingRequestWrapper servletRequest) {
        return StringUtils.isEmpty(servletRequest.getQueryString()) ? "" : servletRequest.getQueryString();
    }

    private void wrapperResponse(HttpServletResponse response) {
        response.setHeader(CommonConstants.FIELD_EAGLEEYE_TRACEID, MDC.get(CommonConstants.TRACE_ID));
    }
}